home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / gdata / tlslite / TLSConnection.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  38.9 KB  |  1,326 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. MAIN CLASS FOR TLS LITE (START HERE!).
  6. '''
  7. from __future__ import generators
  8. import socket
  9. from utils.compat import formatExceptionTrace
  10. from TLSRecordLayer import TLSRecordLayer
  11. from Session import Session
  12. from constants import *
  13. from utils.cryptomath import getRandomBytes
  14. from errors import *
  15. from messages import *
  16. from mathtls import *
  17. from HandshakeSettings import HandshakeSettings
  18.  
  19. class TLSConnection(TLSRecordLayer):
  20.     '''
  21.     This class wraps a socket and provides TLS handshaking and data
  22.     transfer.
  23.  
  24.     To use this class, create a new instance, passing a connected
  25.     socket into the constructor.  Then call some handshake function.
  26.     If the handshake completes without raising an exception, then a TLS
  27.     connection has been negotiated.  You can transfer data over this
  28.     connection as if it were a socket.
  29.  
  30.     This class provides both synchronous and asynchronous versions of
  31.     its key functions.  The synchronous versions should be used when
  32.     writing single-or multi-threaded code using blocking sockets.  The
  33.     asynchronous versions should be used when performing asynchronous,
  34.     event-based I/O with non-blocking sockets.
  35.  
  36.     Asynchronous I/O is a complicated subject; typically, you should
  37.     not use the asynchronous functions directly, but should use some
  38.     framework like asyncore or Twisted which TLS Lite integrates with
  39.     (see
  40.     L{tlslite.integration.TLSAsyncDispatcherMixIn.TLSAsyncDispatcherMixIn} or
  41.     L{tlslite.integration.TLSTwistedProtocolWrapper.TLSTwistedProtocolWrapper}).
  42.     '''
  43.     
  44.     def __init__(self, sock):
  45.         '''Create a new TLSConnection instance.
  46.  
  47.         @param sock: The socket data will be transmitted on.  The
  48.         socket should already be connected.  It may be in blocking or
  49.         non-blocking mode.
  50.  
  51.         @type sock: L{socket.socket}
  52.         '''
  53.         TLSRecordLayer.__init__(self, sock)
  54.  
  55.     
  56.     def handshakeClientSRP(self, username, password, session = None, settings = None, checker = None, async = False):
  57.         """Perform an SRP handshake in the role of client.
  58.  
  59.         This function performs a TLS/SRP handshake.  SRP mutually
  60.         authenticates both parties to each other using only a
  61.         username and password.  This function may also perform a
  62.         combined SRP and server-certificate handshake, if the server
  63.         chooses to authenticate itself with a certificate chain in
  64.         addition to doing SRP.
  65.  
  66.         TLS/SRP is non-standard.  Most TLS implementations don't
  67.         support it.  See
  68.         U{http://www.ietf.org/html.charters/tls-charter.html} or
  69.         U{http://trevp.net/tlssrp/} for the latest information on
  70.         TLS/SRP.
  71.  
  72.         Like any handshake function, this can be called on a closed
  73.         TLS connection, or on a TLS connection that is already open.
  74.         If called on an open connection it performs a re-handshake.
  75.  
  76.         If the function completes without raising an exception, the
  77.         TLS connection will be open and available for data transfer.
  78.  
  79.         If an exception is raised, the connection will have been
  80.         automatically closed (if it was ever open).
  81.  
  82.         @type username: str
  83.         @param username: The SRP username.
  84.  
  85.         @type password: str
  86.         @param password: The SRP password.
  87.  
  88.         @type session: L{tlslite.Session.Session}
  89.         @param session: A TLS session to attempt to resume.  This
  90.         session must be an SRP session performed with the same username
  91.         and password as were passed in.  If the resumption does not
  92.         succeed, a full SRP handshake will be performed.
  93.  
  94.         @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
  95.         @param settings: Various settings which can be used to control
  96.         the ciphersuites, certificate types, and SSL/TLS versions
  97.         offered by the client.
  98.  
  99.         @type checker: L{tlslite.Checker.Checker}
  100.         @param checker: A Checker instance.  This instance will be
  101.         invoked to examine the other party's authentication
  102.         credentials, if the handshake completes succesfully.
  103.  
  104.         @type async: bool
  105.         @param async: If False, this function will block until the
  106.         handshake is completed.  If True, this function will return a
  107.         generator.  Successive invocations of the generator will
  108.         return 0 if it is waiting to read from the socket, 1 if it is
  109.         waiting to write to the socket, or will raise StopIteration if
  110.         the handshake operation is completed.
  111.  
  112.         @rtype: None or an iterable
  113.         @return: If 'async' is True, a generator object will be
  114.         returned.
  115.  
  116.         @raise socket.error: If a socket error occurs.
  117.         @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed
  118.         without a preceding alert.
  119.         @raise tlslite.errors.TLSAlert: If a TLS alert is signalled.
  120.         @raise tlslite.errors.TLSAuthenticationError: If the checker
  121.         doesn't like the other party's authentication credentials.
  122.         """
  123.         handshaker = self._handshakeClientAsync(srpParams = (username, password), session = session, settings = settings, checker = checker)
  124.         if async:
  125.             return handshaker
  126.         for result in handshaker:
  127.             pass
  128.         
  129.  
  130.     
  131.     def handshakeClientCert(self, certChain = None, privateKey = None, session = None, settings = None, checker = None, async = False):
  132.         """Perform a certificate-based handshake in the role of client.
  133.  
  134.         This function performs an SSL or TLS handshake.  The server
  135.         will authenticate itself using an X.509 or cryptoID certificate
  136.         chain.  If the handshake succeeds, the server's certificate
  137.         chain will be stored in the session's serverCertChain attribute.
  138.         Unless a checker object is passed in, this function does no
  139.         validation or checking of the server's certificate chain.
  140.  
  141.         If the server requests client authentication, the
  142.         client will send the passed-in certificate chain, and use the
  143.         passed-in private key to authenticate itself.  If no
  144.         certificate chain and private key were passed in, the client
  145.         will attempt to proceed without client authentication.  The
  146.         server may or may not allow this.
  147.  
  148.         Like any handshake function, this can be called on a closed
  149.         TLS connection, or on a TLS connection that is already open.
  150.         If called on an open connection it performs a re-handshake.
  151.  
  152.         If the function completes without raising an exception, the
  153.         TLS connection will be open and available for data transfer.
  154.  
  155.         If an exception is raised, the connection will have been
  156.         automatically closed (if it was ever open).
  157.  
  158.         @type certChain: L{tlslite.X509CertChain.X509CertChain} or
  159.         L{cryptoIDlib.CertChain.CertChain}
  160.         @param certChain: The certificate chain to be used if the
  161.         server requests client authentication.
  162.  
  163.         @type privateKey: L{tlslite.utils.RSAKey.RSAKey}
  164.         @param privateKey: The private key to be used if the server
  165.         requests client authentication.
  166.  
  167.         @type session: L{tlslite.Session.Session}
  168.         @param session: A TLS session to attempt to resume.  If the
  169.         resumption does not succeed, a full handshake will be
  170.         performed.
  171.  
  172.         @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
  173.         @param settings: Various settings which can be used to control
  174.         the ciphersuites, certificate types, and SSL/TLS versions
  175.         offered by the client.
  176.  
  177.         @type checker: L{tlslite.Checker.Checker}
  178.         @param checker: A Checker instance.  This instance will be
  179.         invoked to examine the other party's authentication
  180.         credentials, if the handshake completes succesfully.
  181.  
  182.         @type async: bool
  183.         @param async: If False, this function will block until the
  184.         handshake is completed.  If True, this function will return a
  185.         generator.  Successive invocations of the generator will
  186.         return 0 if it is waiting to read from the socket, 1 if it is
  187.         waiting to write to the socket, or will raise StopIteration if
  188.         the handshake operation is completed.
  189.  
  190.         @rtype: None or an iterable
  191.         @return: If 'async' is True, a generator object will be
  192.         returned.
  193.  
  194.         @raise socket.error: If a socket error occurs.
  195.         @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed
  196.         without a preceding alert.
  197.         @raise tlslite.errors.TLSAlert: If a TLS alert is signalled.
  198.         @raise tlslite.errors.TLSAuthenticationError: If the checker
  199.         doesn't like the other party's authentication credentials.
  200.         """
  201.         handshaker = self._handshakeClientAsync(certParams = (certChain, privateKey), session = session, settings = settings, checker = checker)
  202.         if async:
  203.             return handshaker
  204.         for result in handshaker:
  205.             pass
  206.         
  207.  
  208.     
  209.     def handshakeClientUnknown(self, srpCallback = None, certCallback = None, session = None, settings = None, checker = None, async = False):
  210.         """Perform a to-be-determined type of handshake in the role of client.
  211.  
  212.         This function performs an SSL or TLS handshake.  If the server
  213.         requests client certificate authentication, the
  214.         certCallback will be invoked and should return a (certChain,
  215.         privateKey) pair.  If the callback returns None, the library
  216.         will attempt to proceed without client authentication.  The
  217.         server may or may not allow this.
  218.  
  219.         If the server requests SRP authentication, the srpCallback
  220.         will be invoked and should return a (username, password) pair.
  221.         If the callback returns None, the local implementation will
  222.         signal a user_canceled error alert.
  223.  
  224.         After the handshake completes, the client can inspect the
  225.         connection's session attribute to determine what type of
  226.         authentication was performed.
  227.  
  228.         Like any handshake function, this can be called on a closed
  229.         TLS connection, or on a TLS connection that is already open.
  230.         If called on an open connection it performs a re-handshake.
  231.  
  232.         If the function completes without raising an exception, the
  233.         TLS connection will be open and available for data transfer.
  234.  
  235.         If an exception is raised, the connection will have been
  236.         automatically closed (if it was ever open).
  237.  
  238.         @type srpCallback: callable
  239.         @param srpCallback: The callback to be used if the server
  240.         requests SRP authentication.  If None, the client will not
  241.         offer support for SRP ciphersuites.
  242.  
  243.         @type certCallback: callable
  244.         @param certCallback: The callback to be used if the server
  245.         requests client certificate authentication.
  246.  
  247.         @type session: L{tlslite.Session.Session}
  248.         @param session: A TLS session to attempt to resume.  If the
  249.         resumption does not succeed, a full handshake will be
  250.         performed.
  251.  
  252.         @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
  253.         @param settings: Various settings which can be used to control
  254.         the ciphersuites, certificate types, and SSL/TLS versions
  255.         offered by the client.
  256.  
  257.         @type checker: L{tlslite.Checker.Checker}
  258.         @param checker: A Checker instance.  This instance will be
  259.         invoked to examine the other party's authentication
  260.         credentials, if the handshake completes succesfully.
  261.  
  262.         @type async: bool
  263.         @param async: If False, this function will block until the
  264.         handshake is completed.  If True, this function will return a
  265.         generator.  Successive invocations of the generator will
  266.         return 0 if it is waiting to read from the socket, 1 if it is
  267.         waiting to write to the socket, or will raise StopIteration if
  268.         the handshake operation is completed.
  269.  
  270.         @rtype: None or an iterable
  271.         @return: If 'async' is True, a generator object will be
  272.         returned.
  273.  
  274.         @raise socket.error: If a socket error occurs.
  275.         @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed
  276.         without a preceding alert.
  277.         @raise tlslite.errors.TLSAlert: If a TLS alert is signalled.
  278.         @raise tlslite.errors.TLSAuthenticationError: If the checker
  279.         doesn't like the other party's authentication credentials.
  280.         """
  281.         handshaker = self._handshakeClientAsync(unknownParams = (srpCallback, certCallback), session = session, settings = settings, checker = checker)
  282.         if async:
  283.             return handshaker
  284.         for result in handshaker:
  285.             pass
  286.         
  287.  
  288.     
  289.     def handshakeClientSharedKey(self, username, sharedKey, settings = None, checker = None, async = False):
  290.         """Perform a shared-key handshake in the role of client.
  291.  
  292.         This function performs a shared-key handshake.  Using shared
  293.         symmetric keys of high entropy (128 bits or greater) mutually
  294.         authenticates both parties to each other.
  295.  
  296.         TLS with shared-keys is non-standard.  Most TLS
  297.         implementations don't support it.  See
  298.         U{http://www.ietf.org/html.charters/tls-charter.html} for the
  299.         latest information on TLS with shared-keys.  If the shared-keys
  300.         Internet-Draft changes or is superceded, TLS Lite will track
  301.         those changes, so the shared-key support in later versions of
  302.         TLS Lite may become incompatible with this version.
  303.  
  304.         Like any handshake function, this can be called on a closed
  305.         TLS connection, or on a TLS connection that is already open.
  306.         If called on an open connection it performs a re-handshake.
  307.  
  308.         If the function completes without raising an exception, the
  309.         TLS connection will be open and available for data transfer.
  310.  
  311.         If an exception is raised, the connection will have been
  312.         automatically closed (if it was ever open).
  313.  
  314.         @type username: str
  315.         @param username: The shared-key username.
  316.  
  317.         @type sharedKey: str
  318.         @param sharedKey: The shared key.
  319.  
  320.         @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
  321.         @param settings: Various settings which can be used to control
  322.         the ciphersuites, certificate types, and SSL/TLS versions
  323.         offered by the client.
  324.  
  325.         @type checker: L{tlslite.Checker.Checker}
  326.         @param checker: A Checker instance.  This instance will be
  327.         invoked to examine the other party's authentication
  328.         credentials, if the handshake completes succesfully.
  329.  
  330.         @type async: bool
  331.         @param async: If False, this function will block until the
  332.         handshake is completed.  If True, this function will return a
  333.         generator.  Successive invocations of the generator will
  334.         return 0 if it is waiting to read from the socket, 1 if it is
  335.         waiting to write to the socket, or will raise StopIteration if
  336.         the handshake operation is completed.
  337.  
  338.         @rtype: None or an iterable
  339.         @return: If 'async' is True, a generator object will be
  340.         returned.
  341.  
  342.         @raise socket.error: If a socket error occurs.
  343.         @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed
  344.         without a preceding alert.
  345.         @raise tlslite.errors.TLSAlert: If a TLS alert is signalled.
  346.         @raise tlslite.errors.TLSAuthenticationError: If the checker
  347.         doesn't like the other party's authentication credentials.
  348.         """
  349.         handshaker = self._handshakeClientAsync(sharedKeyParams = (username, sharedKey), settings = settings, checker = checker)
  350.         if async:
  351.             return handshaker
  352.         for result in handshaker:
  353.             pass
  354.         
  355.  
  356.     
  357.     def _handshakeClientAsync(self, srpParams = (), certParams = (), unknownParams = (), sharedKeyParams = (), session = None, settings = None, checker = None, recursive = False):
  358.         handshaker = self._handshakeClientAsyncHelper(srpParams = srpParams, certParams = certParams, unknownParams = unknownParams, sharedKeyParams = sharedKeyParams, session = session, settings = settings, recursive = recursive)
  359.         for result in self._handshakeWrapperAsync(handshaker, checker):
  360.             yield result
  361.         
  362.  
  363.     
  364.     def _handshakeClientAsyncHelper(self, srpParams, certParams, unknownParams, sharedKeyParams, session, settings, recursive):
  365.         if not recursive:
  366.             self._handshakeStart(client = True)
  367.         
  368.         srpUsername = None
  369.         password = None
  370.         clientCertChain = None
  371.         privateKey = None
  372.         srpCallback = None
  373.         certCallback = None
  374.         if srpParams:
  375.             (srpUsername, password) = srpParams
  376.         elif certParams:
  377.             (clientCertChain, privateKey) = certParams
  378.         elif unknownParams:
  379.             (srpCallback, certCallback) = unknownParams
  380.         elif sharedKeyParams:
  381.             session = Session()._createSharedKey(*sharedKeyParams)
  382.         
  383.         if not settings:
  384.             settings = HandshakeSettings()
  385.         
  386.         settings = settings._filter()
  387.         if srpUsername and not password:
  388.             raise ValueError('Caller passed a username but no password')
  389.         not password
  390.         if password and not srpUsername:
  391.             raise ValueError('Caller passed a password but no username')
  392.         not srpUsername
  393.         if clientCertChain and not privateKey:
  394.             raise ValueError('Caller passed a certChain but no privateKey')
  395.         not privateKey
  396.         if privateKey and not clientCertChain:
  397.             raise ValueError('Caller passed a privateKey but no certChain')
  398.         not clientCertChain
  399.         if clientCertChain:
  400.             foundType = False
  401.             
  402.             try:
  403.                 import cryptoIDlib.CertChain as cryptoIDlib
  404.                 if isinstance(clientCertChain, cryptoIDlib.CertChain.CertChain):
  405.                     if 'cryptoID' not in settings.certificateTypes:
  406.                         raise ValueError("Client certificate doesn't match Handshake Settings")
  407.                     'cryptoID' not in settings.certificateTypes
  408.                     settings.certificateTypes = [
  409.                         'cryptoID']
  410.                     foundType = True
  411.             except ImportError:
  412.                 pass
  413.  
  414.             if not foundType and isinstance(clientCertChain, X509CertChain):
  415.                 if 'x509' not in settings.certificateTypes:
  416.                     raise ValueError("Client certificate doesn't match Handshake Settings")
  417.                 'x509' not in settings.certificateTypes
  418.                 settings.certificateTypes = [
  419.                     'x509']
  420.                 foundType = True
  421.             
  422.             if not foundType:
  423.                 raise ValueError('Unrecognized certificate type')
  424.             foundType
  425.         
  426.         if session:
  427.             if not session.valid():
  428.                 session = None
  429.             elif session.resumable and session.srpUsername != srpUsername:
  430.                 raise ValueError("Session username doesn't match")
  431.             
  432.         
  433.         if srpUsername and self.fault == Fault.badUsername:
  434.             srpUsername += 'GARBAGE'
  435.         
  436.         if password and self.fault == Fault.badPassword:
  437.             password += 'GARBAGE'
  438.         
  439.         if sharedKeyParams:
  440.             identifier = sharedKeyParams[0]
  441.             sharedKey = sharedKeyParams[1]
  442.             if self.fault == Fault.badIdentifier:
  443.                 identifier += 'GARBAGE'
  444.                 session = Session()._createSharedKey(identifier, sharedKey)
  445.             elif self.fault == Fault.badSharedKey:
  446.                 sharedKey += 'GARBAGE'
  447.                 session = Session()._createSharedKey(identifier, sharedKey)
  448.             
  449.         
  450.         serverCertChain = None
  451.         cipherSuite = 0
  452.         certificateType = CertificateType.x509
  453.         premasterSecret = None
  454.         clientRandom = getRandomBytes(32)
  455.         cipherSuites = []
  456.         if srpParams:
  457.             cipherSuites += CipherSuite.getSrpRsaSuites(settings.cipherNames)
  458.             cipherSuites += CipherSuite.getSrpSuites(settings.cipherNames)
  459.         elif certParams:
  460.             cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames)
  461.         elif unknownParams:
  462.             if srpCallback:
  463.                 cipherSuites += CipherSuite.getSrpRsaSuites(settings.cipherNames)
  464.                 cipherSuites += CipherSuite.getSrpSuites(settings.cipherNames)
  465.             
  466.             cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames)
  467.         elif sharedKeyParams:
  468.             cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames)
  469.         else:
  470.             cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames)
  471.         certificateTypes = settings._getCertificateTypes()
  472.         self.version = settings.maxVersion
  473.         if session:
  474.             if not sharedKeyParams and session.cipherSuite not in cipherSuites:
  475.                 raise ValueError("Session's cipher suite not consistent with parameters")
  476.             session.cipherSuite not in cipherSuites
  477.             clientHello = ClientHello()
  478.             clientHello.create(settings.maxVersion, clientRandom, session.sessionID, cipherSuites, certificateTypes, session.srpUsername)
  479.         else:
  480.             clientHello = ClientHello()
  481.             clientHello.create(settings.maxVersion, clientRandom, createByteArraySequence([]), cipherSuites, certificateTypes, srpUsername)
  482.         for result in self._sendMsg(clientHello):
  483.             yield result
  484.         
  485.         for result in self._getMsg((ContentType.handshake, ContentType.alert), HandshakeType.server_hello):
  486.             if result in (0, 1):
  487.                 yield result
  488.                 continue
  489.         
  490.         msg = result
  491.         if isinstance(msg, ServerHello):
  492.             serverHello = msg
  493.         elif isinstance(msg, Alert):
  494.             alert = msg
  495.             if alert.description != AlertDescription.missing_srp_username:
  496.                 self._shutdown(False)
  497.                 raise TLSRemoteAlert(alert)
  498.             alert.description != AlertDescription.missing_srp_username
  499.             if not srpCallback:
  500.                 for result in self._sendError(AlertDescription.unexpected_message):
  501.                     yield result
  502.                 
  503.             
  504.             srpParams = srpCallback()
  505.             if srpParams == None:
  506.                 for result in self._sendError(AlertDescription.user_canceled):
  507.                     yield result
  508.                 
  509.             
  510.             for result in self._handshakeClientAsyncHelper(srpParams, None, None, None, None, settings, True):
  511.                 yield result
  512.             
  513.             return None
  514.         self.version = serverHello.server_version
  515.         self._versionCheck = True
  516.         if serverHello.server_version < settings.minVersion:
  517.             for result in self._sendError(AlertDescription.protocol_version, 'Too old version: %s' % str(serverHello.server_version)):
  518.                 yield result
  519.             
  520.         
  521.         if serverHello.server_version > settings.maxVersion:
  522.             for result in self._sendError(AlertDescription.protocol_version, 'Too new version: %s' % str(serverHello.server_version)):
  523.                 yield result
  524.             
  525.         
  526.         if serverHello.cipher_suite not in cipherSuites:
  527.             for result in self._sendError(AlertDescription.illegal_parameter, 'Server responded with incorrect ciphersuite'):
  528.                 yield result
  529.             
  530.         
  531.         if serverHello.certificate_type not in certificateTypes:
  532.             for result in self._sendError(AlertDescription.illegal_parameter, 'Server responded with incorrect certificate type'):
  533.                 yield result
  534.             
  535.         
  536.         if serverHello.compression_method != 0:
  537.             for result in self._sendError(AlertDescription.illegal_parameter, 'Server responded with incorrect compression method'):
  538.                 yield result
  539.             
  540.         
  541.         serverRandom = serverHello.random
  542.         if session and session.sessionID and serverHello.session_id == session.sessionID:
  543.             if sharedKeyParams:
  544.                 session.cipherSuite = serverHello.cipher_suite
  545.             elif serverHello.cipher_suite != session.cipherSuite:
  546.                 for result in self._sendError(AlertDescription.illegal_parameter, "Server's ciphersuite doesn't match session"):
  547.                     yield result
  548.                 
  549.             
  550.             self.session = session
  551.             self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations)
  552.             for result in self._getFinished():
  553.                 yield result
  554.             
  555.             for result in self._sendFinished():
  556.                 yield result
  557.             
  558.             self._handshakeDone(resumed = True)
  559.         elif sharedKeyParams:
  560.             for result in self._sendError(AlertDescription.user_canceled, 'Was expecting a shared-key resumption'):
  561.                 yield result
  562.             
  563.         
  564.         cipherSuite = serverHello.cipher_suite
  565.         certificateType = serverHello.certificate_type
  566.         if cipherSuite in CipherSuite.srpSuites:
  567.             for result in self._getMsg(ContentType.handshake, HandshakeType.server_key_exchange, cipherSuite):
  568.                 if result in (0, 1):
  569.                     yield result
  570.                     continue
  571.             
  572.             serverKeyExchange = result
  573.             for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done):
  574.                 if result in (0, 1):
  575.                     yield result
  576.                     continue
  577.             
  578.             serverHelloDone = result
  579.         elif cipherSuite in CipherSuite.srpRsaSuites:
  580.             for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType):
  581.                 if result in (0, 1):
  582.                     yield result
  583.                     continue
  584.             
  585.             serverCertificate = result
  586.             for result in self._getMsg(ContentType.handshake, HandshakeType.server_key_exchange, cipherSuite):
  587.                 if result in (0, 1):
  588.                     yield result
  589.                     continue
  590.             
  591.             serverKeyExchange = result
  592.             for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done):
  593.                 if result in (0, 1):
  594.                     yield result
  595.                     continue
  596.             
  597.             serverHelloDone = result
  598.         elif cipherSuite in CipherSuite.rsaSuites:
  599.             for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType):
  600.                 if result in (0, 1):
  601.                     yield result
  602.                     continue
  603.             
  604.             serverCertificate = result
  605.             for result in self._getMsg(ContentType.handshake, (HandshakeType.server_hello_done, HandshakeType.certificate_request)):
  606.                 if result in (0, 1):
  607.                     yield result
  608.                     continue
  609.             
  610.             msg = result
  611.             certificateRequest = None
  612.             if isinstance(msg, CertificateRequest):
  613.                 certificateRequest = msg
  614.                 for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done):
  615.                     if result in (0, 1):
  616.                         yield result
  617.                         continue
  618.                 
  619.                 serverHelloDone = result
  620.             elif isinstance(msg, ServerHelloDone):
  621.                 serverHelloDone = msg
  622.             
  623.         else:
  624.             raise AssertionError()
  625.         if cipherSuite in CipherSuite.srpSuites in CipherSuite.srpSuites + CipherSuite.srpRsaSuites:
  626.             N = serverKeyExchange.srp_N
  627.             g = serverKeyExchange.srp_g
  628.             s = serverKeyExchange.srp_s
  629.             B = serverKeyExchange.srp_B
  630.             if (g, N) not in goodGroupParameters:
  631.                 for result in self._sendError(AlertDescription.untrusted_srp_parameters, 'Unknown group parameters'):
  632.                     yield result
  633.                 
  634.             
  635.             if numBits(N) < settings.minKeySize:
  636.                 for result in self._sendError(AlertDescription.untrusted_srp_parameters, 'N value is too small: %d' % numBits(N)):
  637.                     yield result
  638.                 
  639.             
  640.             if numBits(N) > settings.maxKeySize:
  641.                 for result in self._sendError(AlertDescription.untrusted_srp_parameters, 'N value is too large: %d' % numBits(N)):
  642.                     yield result
  643.                 
  644.             
  645.             if B % N == 0:
  646.                 for result in self._sendError(AlertDescription.illegal_parameter, 'Suspicious B value'):
  647.                     yield result
  648.                 
  649.             
  650.             if cipherSuite in CipherSuite.srpRsaSuites:
  651.                 hashBytes = serverKeyExchange.hash(clientRandom, serverRandom)
  652.                 sigBytes = serverKeyExchange.signature
  653.                 if len(sigBytes) == 0:
  654.                     for result in self._sendError(AlertDescription.illegal_parameter, 'Server sent an SRP ServerKeyExchange message without a signature'):
  655.                         yield result
  656.                     
  657.                 
  658.                 for result in self._getKeyFromChain(serverCertificate, settings):
  659.                     if result in (0, 1):
  660.                         yield result
  661.                         continue
  662.                 
  663.                 (publicKey, serverCertChain) = result
  664.                 if not publicKey.verify(sigBytes, hashBytes):
  665.                     for result in self._sendError(AlertDescription.decrypt_error, 'Signature failed to verify'):
  666.                         yield result
  667.                     
  668.                 
  669.             
  670.             a = bytesToNumber(getRandomBytes(32))
  671.             A = powMod(g, a, N)
  672.             x = makeX(bytesToString(s), srpUsername, password)
  673.             v = powMod(g, x, N)
  674.             u = makeU(N, A, B)
  675.             k = makeK(N, g)
  676.             S = powMod((B - k * v) % N, a + u * x, N)
  677.             if self.fault == Fault.badA:
  678.                 A = N
  679.                 S = 0
  680.             
  681.             premasterSecret = numberToBytes(S)
  682.             for result in self._sendMsg(ClientKeyExchange(cipherSuite).createSRP(A)):
  683.                 yield result
  684.             
  685.         elif cipherSuite in CipherSuite.rsaSuites:
  686.             if certificateRequest:
  687.                 if unknownParams and certCallback:
  688.                     certParamsNew = certCallback()
  689.                     if certParamsNew:
  690.                         (clientCertChain, privateKey) = certParamsNew
  691.                     
  692.                 
  693.             
  694.             for result in self._getKeyFromChain(serverCertificate, settings):
  695.                 if result in (0, 1):
  696.                     yield result
  697.                     continue
  698.             
  699.             (publicKey, serverCertChain) = result
  700.             premasterSecret = getRandomBytes(48)
  701.             premasterSecret[0] = settings.maxVersion[0]
  702.             premasterSecret[1] = settings.maxVersion[1]
  703.             if self.fault == Fault.badPremasterPadding:
  704.                 premasterSecret[0] = 5
  705.             
  706.             if self.fault == Fault.shortPremasterSecret:
  707.                 premasterSecret = premasterSecret[:-1]
  708.             
  709.             encryptedPreMasterSecret = publicKey.encrypt(premasterSecret)
  710.             if certificateRequest:
  711.                 clientCertificate = Certificate(certificateType)
  712.                 if clientCertChain:
  713.                     wrongType = False
  714.                     if certificateType == CertificateType.x509:
  715.                         if not isinstance(clientCertChain, X509CertChain):
  716.                             wrongType = True
  717.                         
  718.                     elif certificateType == CertificateType.cryptoID:
  719.                         if not isinstance(clientCertChain, cryptoIDlib.CertChain.CertChain):
  720.                             wrongType = True
  721.                         
  722.                     
  723.                     if wrongType:
  724.                         for result in self._sendError(AlertDescription.handshake_failure, 'Client certificate is of wrong type'):
  725.                             yield result
  726.                         
  727.                     
  728.                     clientCertificate.create(clientCertChain)
  729.                 
  730.                 for result in self._sendMsg(clientCertificate):
  731.                     yield result
  732.                 
  733.             else:
  734.                 privateKey = None
  735.                 clientCertChain = None
  736.             clientKeyExchange = ClientKeyExchange(cipherSuite, self.version)
  737.             clientKeyExchange.createRSA(encryptedPreMasterSecret)
  738.             for result in self._sendMsg(clientKeyExchange):
  739.                 yield result
  740.             
  741.             if certificateRequest and privateKey:
  742.                 if self.version == (3, 0):
  743.                     session = Session()
  744.                     session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom)
  745.                     verifyBytes = self._calcSSLHandshakeHash(session.masterSecret, '')
  746.                 elif self.version in ((3, 1), (3, 2)):
  747.                     verifyBytes = stringToBytes(self._handshake_md5.digest() + self._handshake_sha.digest())
  748.                 
  749.                 if self.fault == Fault.badVerifyMessage:
  750.                     verifyBytes[0] = (verifyBytes[0] + 1) % 256
  751.                 
  752.                 signedBytes = privateKey.sign(verifyBytes)
  753.                 certificateVerify = CertificateVerify()
  754.                 certificateVerify.create(signedBytes)
  755.                 for result in self._sendMsg(certificateVerify):
  756.                     yield result
  757.                 
  758.             
  759.         
  760.         self.session = Session()
  761.         self.session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom)
  762.         self.session.sessionID = serverHello.session_id
  763.         self.session.cipherSuite = cipherSuite
  764.         self.session.srpUsername = srpUsername
  765.         self.session.clientCertChain = clientCertChain
  766.         self.session.serverCertChain = serverCertChain
  767.         self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations)
  768.         for result in self._sendFinished():
  769.             yield result
  770.         
  771.         for result in self._getFinished():
  772.             yield result
  773.         
  774.         self.session._setResumable(True)
  775.         self._handshakeDone(resumed = False)
  776.  
  777.     
  778.     def handshakeServer(self, sharedKeyDB = None, verifierDB = None, certChain = None, privateKey = None, reqCert = False, sessionCache = None, settings = None, checker = None):
  779.         """Perform a handshake in the role of server.
  780.  
  781.         This function performs an SSL or TLS handshake.  Depending on
  782.         the arguments and the behavior of the client, this function can
  783.         perform a shared-key, SRP, or certificate-based handshake.  It
  784.         can also perform a combined SRP and server-certificate
  785.         handshake.
  786.  
  787.         Like any handshake function, this can be called on a closed
  788.         TLS connection, or on a TLS connection that is already open.
  789.         If called on an open connection it performs a re-handshake.
  790.         This function does not send a Hello Request message before
  791.         performing the handshake, so if re-handshaking is required,
  792.         the server must signal the client to begin the re-handshake
  793.         through some other means.
  794.  
  795.         If the function completes without raising an exception, the
  796.         TLS connection will be open and available for data transfer.
  797.  
  798.         If an exception is raised, the connection will have been
  799.         automatically closed (if it was ever open).
  800.  
  801.         @type sharedKeyDB: L{tlslite.SharedKeyDB.SharedKeyDB}
  802.         @param sharedKeyDB: A database of shared symmetric keys
  803.         associated with usernames.  If the client performs a
  804.         shared-key handshake, the session's sharedKeyUsername
  805.         attribute will be set.
  806.  
  807.         @type verifierDB: L{tlslite.VerifierDB.VerifierDB}
  808.         @param verifierDB: A database of SRP password verifiers
  809.         associated with usernames.  If the client performs an SRP
  810.         handshake, the session's srpUsername attribute will be set.
  811.  
  812.         @type certChain: L{tlslite.X509CertChain.X509CertChain} or
  813.         L{cryptoIDlib.CertChain.CertChain}
  814.         @param certChain: The certificate chain to be used if the
  815.         client requests server certificate authentication.
  816.  
  817.         @type privateKey: L{tlslite.utils.RSAKey.RSAKey}
  818.         @param privateKey: The private key to be used if the client
  819.         requests server certificate authentication.
  820.  
  821.         @type reqCert: bool
  822.         @param reqCert: Whether to request client certificate
  823.         authentication.  This only applies if the client chooses server
  824.         certificate authentication; if the client chooses SRP or
  825.         shared-key authentication, this will be ignored.  If the client
  826.         performs a client certificate authentication, the sessions's
  827.         clientCertChain attribute will be set.
  828.  
  829.         @type sessionCache: L{tlslite.SessionCache.SessionCache}
  830.         @param sessionCache: An in-memory cache of resumable sessions.
  831.         The client can resume sessions from this cache.  Alternatively,
  832.         if the client performs a full handshake, a new session will be
  833.         added to the cache.
  834.  
  835.         @type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
  836.         @param settings: Various settings which can be used to control
  837.         the ciphersuites and SSL/TLS version chosen by the server.
  838.  
  839.         @type checker: L{tlslite.Checker.Checker}
  840.         @param checker: A Checker instance.  This instance will be
  841.         invoked to examine the other party's authentication
  842.         credentials, if the handshake completes succesfully.
  843.  
  844.         @raise socket.error: If a socket error occurs.
  845.         @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed
  846.         without a preceding alert.
  847.         @raise tlslite.errors.TLSAlert: If a TLS alert is signalled.
  848.         @raise tlslite.errors.TLSAuthenticationError: If the checker
  849.         doesn't like the other party's authentication credentials.
  850.         """
  851.         for result in self.handshakeServerAsync(sharedKeyDB, verifierDB, certChain, privateKey, reqCert, sessionCache, settings, checker):
  852.             pass
  853.         
  854.  
  855.     
  856.     def handshakeServerAsync(self, sharedKeyDB = None, verifierDB = None, certChain = None, privateKey = None, reqCert = False, sessionCache = None, settings = None, checker = None):
  857.         '''Start a server handshake operation on the TLS connection.
  858.  
  859.         This function returns a generator which behaves similarly to
  860.         handshakeServer().  Successive invocations of the generator
  861.         will return 0 if it is waiting to read from the socket, 1 if it is
  862.         waiting to write to the socket, or it will raise StopIteration
  863.         if the handshake operation is complete.
  864.  
  865.         @rtype: iterable
  866.         @return: A generator; see above for details.
  867.         '''
  868.         handshaker = self._handshakeServerAsyncHelper(sharedKeyDB = sharedKeyDB, verifierDB = verifierDB, certChain = certChain, privateKey = privateKey, reqCert = reqCert, sessionCache = sessionCache, settings = settings)
  869.         for result in self._handshakeWrapperAsync(handshaker, checker):
  870.             yield result
  871.         
  872.  
  873.     
  874.     def _handshakeServerAsyncHelper(self, sharedKeyDB, verifierDB, certChain, privateKey, reqCert, sessionCache, settings):
  875.         self._handshakeStart(client = False)
  876.         if not sharedKeyDB and not verifierDB and not certChain:
  877.             raise ValueError('Caller passed no authentication credentials')
  878.         not certChain
  879.         if certChain and not privateKey:
  880.             raise ValueError('Caller passed a certChain but no privateKey')
  881.         not privateKey
  882.         if privateKey and not certChain:
  883.             raise ValueError('Caller passed a privateKey but no certChain')
  884.         not certChain
  885.         if not settings:
  886.             settings = HandshakeSettings()
  887.         
  888.         settings = settings._filter()
  889.         cipherSuites = []
  890.         if verifierDB:
  891.             if certChain:
  892.                 cipherSuites += CipherSuite.getSrpRsaSuites(settings.cipherNames)
  893.             
  894.             cipherSuites += CipherSuite.getSrpSuites(settings.cipherNames)
  895.         
  896.         if sharedKeyDB or certChain:
  897.             cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames)
  898.         
  899.         certificateType = None
  900.         if certChain:
  901.             
  902.             try:
  903.                 import cryptoIDlib.CertChain as cryptoIDlib
  904.                 if isinstance(certChain, cryptoIDlib.CertChain.CertChain):
  905.                     certificateType = CertificateType.cryptoID
  906.             except ImportError:
  907.                 pass
  908.  
  909.             if isinstance(certChain, X509CertChain):
  910.                 certificateType = CertificateType.x509
  911.             
  912.             if certificateType == None:
  913.                 raise ValueError('Unrecognized certificate type')
  914.             certificateType == None
  915.         
  916.         clientCertChain = None
  917.         serverCertChain = None
  918.         postFinishedError = None
  919.         self.version = settings.maxVersion
  920.         for result in self._getMsg(ContentType.handshake, HandshakeType.client_hello):
  921.             if result in (0, 1):
  922.                 yield result
  923.                 continue
  924.         
  925.         clientHello = result
  926.         if clientHello.client_version < settings.minVersion:
  927.             self.version = settings.minVersion
  928.             for result in self._sendError(AlertDescription.protocol_version, 'Too old version: %s' % str(clientHello.client_version)):
  929.                 yield result
  930.             
  931.         elif clientHello.client_version > settings.maxVersion:
  932.             self.version = settings.maxVersion
  933.         else:
  934.             self.version = clientHello.client_version
  935.         clientRandom = clientHello.random
  936.         serverRandom = getRandomBytes(32)
  937.         for cipherSuite in cipherSuites:
  938.             if cipherSuite in clientHello.cipher_suites:
  939.                 break
  940.                 continue
  941.         else:
  942.             for result in self._sendError(AlertDescription.handshake_failure):
  943.                 yield result
  944.             
  945.         if clientHello.session_id:
  946.             if sharedKeyDB or sessionCache:
  947.                 session = None
  948.                 if sharedKeyDB and len(clientHello.session_id) == 16:
  949.                     
  950.                     try:
  951.                         for x in range(16):
  952.                             if clientHello.session_id[x] == 0:
  953.                                 break
  954.                                 continue
  955.                         
  956.                         self.allegedSharedKeyUsername = bytesToString(clientHello.session_id[:x])
  957.                         session = sharedKeyDB[self.allegedSharedKeyUsername]
  958.                         if not session.sharedKey:
  959.                             raise AssertionError()
  960.                         session.sharedKey
  961.                         session.cipherSuite = cipherSuite
  962.                     except KeyError:
  963.                         pass
  964.                     except:
  965.                         None<EXCEPTION MATCH>KeyError
  966.                     
  967.  
  968.                 None<EXCEPTION MATCH>KeyError
  969.                 if sessionCache and not session:
  970.                     
  971.                     try:
  972.                         session = sessionCache[bytesToString(clientHello.session_id)]
  973.                         if session.sharedKey:
  974.                             raise AssertionError()
  975.                         session.sharedKey
  976.                         if not session.resumable:
  977.                             raise AssertionError()
  978.                         session.resumable
  979.                         if session.cipherSuite not in cipherSuites:
  980.                             for result in self._sendError(AlertDescription.handshake_failure):
  981.                                 yield result
  982.                             
  983.                         
  984.                         if session.cipherSuite not in clientHello.cipher_suites:
  985.                             for result in self._sendError(AlertDescription.handshake_failure):
  986.                                 yield result
  987.                             
  988.                         
  989.                         if clientHello.srp_username:
  990.                             if clientHello.srp_username != session.srpUsername:
  991.                                 for result in self._sendError(AlertDescription.handshake_failure):
  992.                                     yield result
  993.                                 
  994.                             
  995.                     except KeyError:
  996.                         pass
  997.                     except:
  998.                         None<EXCEPTION MATCH>KeyError
  999.                     
  1000.  
  1001.                 None<EXCEPTION MATCH>KeyError
  1002.                 if session:
  1003.                     self.session = session
  1004.                     serverHello = ServerHello()
  1005.                     serverHello.create(self.version, serverRandom, session.sessionID, session.cipherSuite, certificateType)
  1006.                     for result in self._sendMsg(serverHello):
  1007.                         yield result
  1008.                     
  1009.                     self._versionCheck = True
  1010.                     self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations)
  1011.                     for result in self._sendFinished():
  1012.                         yield result
  1013.                     
  1014.                     for result in self._getFinished():
  1015.                         yield result
  1016.                     
  1017.                     self._handshakeDone(resumed = True)
  1018.                     return None
  1019.             
  1020.         if cipherSuite in CipherSuite.rsaSuites and not certChain:
  1021.             for result in self._sendError(AlertDescription.handshake_failure):
  1022.                 yield result
  1023.             
  1024.         
  1025.         if cipherSuite in CipherSuite.rsaSuites + CipherSuite.srpRsaSuites:
  1026.             if certificateType not in clientHello.certificate_types:
  1027.                 for result in self._sendError(AlertDescription.handshake_failure, "the client doesn't support my certificate type"):
  1028.                     yield result
  1029.                 
  1030.             
  1031.             serverCertChain = certChain
  1032.         
  1033.         if sessionCache:
  1034.             sessionID = getRandomBytes(32)
  1035.         else:
  1036.             sessionID = createByteArraySequence([])
  1037.         if cipherSuite in CipherSuite.srpSuites + CipherSuite.srpRsaSuites:
  1038.             if not clientHello.srp_username:
  1039.                 for result in self._sendMsg(Alert().create(AlertDescription.missing_srp_username, AlertLevel.warning)):
  1040.                     yield result
  1041.                 
  1042.                 for result in self._getMsg(ContentType.handshake, HandshakeType.client_hello):
  1043.                     if result in (0, 1):
  1044.                         yield result
  1045.                         continue
  1046.                 
  1047.                 clientHello = result
  1048.                 if clientHello.client_version < settings.minVersion:
  1049.                     self.version = settings.minVersion
  1050.                     for result in self._sendError(AlertDescription.protocol_version, 'Too old version: %s' % str(clientHello.client_version)):
  1051.                         yield result
  1052.                     
  1053.                 elif clientHello.client_version > settings.maxVersion:
  1054.                     self.version = settings.maxVersion
  1055.                 else:
  1056.                     self.version = clientHello.client_version
  1057.                 cipherSuites = _[1]
  1058.                 for cipherSuite in cipherSuites:
  1059.                     if cipherSuite in clientHello.cipher_suites:
  1060.                         break
  1061.                         continue
  1062.                     []
  1063.                 else:
  1064.                     for result in self._sendError(AlertDescription.handshake_failure):
  1065.                         yield result
  1066.                         []
  1067.                     
  1068.                 clientRandom = clientHello.random
  1069.                 serverRandom = getRandomBytes(32)
  1070.                 if not clientHello.srp_username:
  1071.                     for result in self._sendError(AlertDescription.illegal_parameter, 'Client resent a hello, but without the SRP username'):
  1072.                         yield result
  1073.                     
  1074.                 
  1075.             
  1076.             self.allegedSrpUsername = clientHello.srp_username
  1077.             
  1078.             try:
  1079.                 entry = verifierDB[self.allegedSrpUsername]
  1080.             except KeyError:
  1081.                 for result in self._sendError(AlertDescription.unknown_srp_username):
  1082.                     yield result
  1083.                 
  1084.  
  1085.             (N, g, s, v) = entry
  1086.             b = bytesToNumber(getRandomBytes(32))
  1087.             k = makeK(N, g)
  1088.             B = (powMod(g, b, N) + k * v) % N
  1089.             serverKeyExchange = ServerKeyExchange(cipherSuite)
  1090.             serverKeyExchange.createSRP(N, g, stringToBytes(s), B)
  1091.             if cipherSuite in CipherSuite.srpRsaSuites:
  1092.                 hashBytes = serverKeyExchange.hash(clientRandom, serverRandom)
  1093.                 serverKeyExchange.signature = privateKey.sign(hashBytes)
  1094.             
  1095.             msgs = []
  1096.             serverHello = ServerHello()
  1097.             serverHello.create(self.version, serverRandom, sessionID, cipherSuite, certificateType)
  1098.             msgs.append(serverHello)
  1099.             if cipherSuite in CipherSuite.srpRsaSuites:
  1100.                 certificateMsg = Certificate(certificateType)
  1101.                 certificateMsg.create(serverCertChain)
  1102.                 msgs.append(certificateMsg)
  1103.             
  1104.             msgs.append(serverKeyExchange)
  1105.             msgs.append(ServerHelloDone())
  1106.             for result in self._sendMsgs(msgs):
  1107.                 yield result
  1108.             
  1109.             self._versionCheck = True
  1110.             for result in self._getMsg(ContentType.handshake, HandshakeType.client_key_exchange, cipherSuite):
  1111.                 if result in (0, 1):
  1112.                     yield result
  1113.                     continue
  1114.             
  1115.             clientKeyExchange = result
  1116.             A = clientKeyExchange.srp_A
  1117.             if A % N == 0:
  1118.                 postFinishedError = (AlertDescription.illegal_parameter, 'Suspicious A value')
  1119.             
  1120.             u = makeU(N, A, B)
  1121.             S = powMod(A * powMod(v, u, N) % N, b, N)
  1122.             premasterSecret = numberToBytes(S)
  1123.         elif cipherSuite in CipherSuite.rsaSuites:
  1124.             msgs = []
  1125.             msgs.append(ServerHello().create(self.version, serverRandom, sessionID, cipherSuite, certificateType))
  1126.             msgs.append(Certificate(certificateType).create(serverCertChain))
  1127.             if reqCert:
  1128.                 msgs.append(CertificateRequest())
  1129.             
  1130.             msgs.append(ServerHelloDone())
  1131.             for result in self._sendMsgs(msgs):
  1132.                 yield result
  1133.             
  1134.             self._versionCheck = True
  1135.             if reqCert:
  1136.                 if self.version == (3, 0):
  1137.                     for result in self._getMsg((ContentType.handshake, ContentType.alert), HandshakeType.certificate, certificateType):
  1138.                         if result in (0, 1):
  1139.                             yield result
  1140.                             continue
  1141.                     
  1142.                     msg = result
  1143.                     if isinstance(msg, Alert):
  1144.                         alert = msg
  1145.                         if alert.description != AlertDescription.no_certificate:
  1146.                             self._shutdown(False)
  1147.                             raise TLSRemoteAlert(alert)
  1148.                         alert.description != AlertDescription.no_certificate
  1149.                     elif isinstance(msg, Certificate):
  1150.                         clientCertificate = msg
  1151.                         if clientCertificate.certChain and clientCertificate.certChain.getNumCerts() != 0:
  1152.                             clientCertChain = clientCertificate.certChain
  1153.                         
  1154.                     else:
  1155.                         raise AssertionError()
  1156.                 isinstance(msg, Alert)
  1157.                 if self.version in ((3, 1), (3, 2)):
  1158.                     for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType):
  1159.                         if result in (0, 1):
  1160.                             yield result
  1161.                             continue
  1162.                     
  1163.                     clientCertificate = result
  1164.                     if clientCertificate.certChain and clientCertificate.certChain.getNumCerts() != 0:
  1165.                         clientCertChain = clientCertificate.certChain
  1166.                     
  1167.                 else:
  1168.                     raise AssertionError()
  1169.             self.version in ((3, 1), (3, 2))
  1170.             for result in self._getMsg(ContentType.handshake, HandshakeType.client_key_exchange, cipherSuite):
  1171.                 if result in (0, 1):
  1172.                     yield result
  1173.                     continue
  1174.             
  1175.             clientKeyExchange = result
  1176.             premasterSecret = privateKey.decrypt(clientKeyExchange.encryptedPreMasterSecret)
  1177.             randomPreMasterSecret = getRandomBytes(48)
  1178.             versionCheck = (premasterSecret[0], premasterSecret[1])
  1179.             if not premasterSecret:
  1180.                 premasterSecret = randomPreMasterSecret
  1181.             elif len(premasterSecret) != 48:
  1182.                 premasterSecret = randomPreMasterSecret
  1183.             elif versionCheck != clientHello.client_version:
  1184.                 if versionCheck != self.version:
  1185.                     premasterSecret = randomPreMasterSecret
  1186.                 
  1187.             
  1188.             if clientCertChain:
  1189.                 if self.version == (3, 0):
  1190.                     session = Session()
  1191.                     session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom)
  1192.                     verifyBytes = self._calcSSLHandshakeHash(session.masterSecret, '')
  1193.                 elif self.version in ((3, 1), (3, 2)):
  1194.                     verifyBytes = stringToBytes(self._handshake_md5.digest() + self._handshake_sha.digest())
  1195.                 
  1196.                 for result in self._getMsg(ContentType.handshake, HandshakeType.certificate_verify):
  1197.                     if result in (0, 1):
  1198.                         yield result
  1199.                         continue
  1200.                 
  1201.                 certificateVerify = result
  1202.                 publicKey = clientCertChain.getEndEntityPublicKey()
  1203.                 if len(publicKey) < settings.minKeySize:
  1204.                     postFinishedError = (AlertDescription.handshake_failure, "Client's public key too small: %d" % len(publicKey))
  1205.                 
  1206.                 if len(publicKey) > settings.maxKeySize:
  1207.                     postFinishedError = (AlertDescription.handshake_failure, "Client's public key too large: %d" % len(publicKey))
  1208.                 
  1209.                 if not publicKey.verify(certificateVerify.signature, verifyBytes):
  1210.                     postFinishedError = (AlertDescription.decrypt_error, 'Signature failed to verify')
  1211.                 
  1212.             
  1213.         
  1214.         self.session = Session()
  1215.         self.session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom)
  1216.         self.session.sessionID = sessionID
  1217.         self.session.cipherSuite = cipherSuite
  1218.         self.session.srpUsername = self.allegedSrpUsername
  1219.         self.session.clientCertChain = clientCertChain
  1220.         self.session.serverCertChain = serverCertChain
  1221.         self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations)
  1222.         for result in self._getFinished():
  1223.             yield result
  1224.         
  1225.         if postFinishedError:
  1226.             for result in self._sendError(*postFinishedError):
  1227.                 yield result
  1228.             
  1229.         
  1230.         for result in self._sendFinished():
  1231.             yield result
  1232.         
  1233.         if sessionCache and sessionID:
  1234.             sessionCache[bytesToString(sessionID)] = self.session
  1235.         
  1236.         self.session._setResumable(True)
  1237.         self._handshakeDone(resumed = False)
  1238.  
  1239.     
  1240.     def _handshakeWrapperAsync(self, handshaker, checker):
  1241.         if not self.fault:
  1242.             
  1243.             try:
  1244.                 for result in handshaker:
  1245.                     yield result
  1246.                 
  1247.                 if checker:
  1248.                     
  1249.                     try:
  1250.                         checker(self)
  1251.                     except TLSAuthenticationError:
  1252.                         alert = Alert().create(AlertDescription.close_notify, AlertLevel.fatal)
  1253.                         for result in self._sendMsg(alert):
  1254.                             yield result
  1255.                         
  1256.                         raise 
  1257.                     except:
  1258.                         None<EXCEPTION MATCH>TLSAuthenticationError
  1259.                     
  1260.  
  1261.                 None<EXCEPTION MATCH>TLSAuthenticationError
  1262.             self._shutdown(False)
  1263.             raise 
  1264.  
  1265.         else:
  1266.             
  1267.             try:
  1268.                 for result in handshaker:
  1269.                     yield result
  1270.                 
  1271.                 if checker:
  1272.                     
  1273.                     try:
  1274.                         checker(self)
  1275.                     except TLSAuthenticationError:
  1276.                         alert = Alert().create(AlertDescription.close_notify, AlertLevel.fatal)
  1277.                         for result in self._sendMsg(alert):
  1278.                             yield result
  1279.                         
  1280.                         raise 
  1281.                     except:
  1282.                         None<EXCEPTION MATCH>TLSAuthenticationError
  1283.                     
  1284.  
  1285.                 None<EXCEPTION MATCH>TLSAuthenticationError
  1286.             except socket.error:
  1287.                 e = None
  1288.                 raise TLSFaultError('socket error!')
  1289.             except TLSAbruptCloseError:
  1290.                 e = None
  1291.                 raise TLSFaultError('abrupt close error!')
  1292.             except TLSAlert:
  1293.                 alert = None
  1294.                 if alert.description not in Fault.faultAlerts[self.fault]:
  1295.                     raise TLSFaultError(str(alert))
  1296.                 alert.description not in Fault.faultAlerts[self.fault]
  1297.             except:
  1298.                 self._shutdown(False)
  1299.                 raise 
  1300.  
  1301.             raise TLSFaultError('No error!')
  1302.         return self.fault
  1303.  
  1304.     
  1305.     def _getKeyFromChain(self, certificate, settings):
  1306.         certChain = certificate.certChain
  1307.         if not certChain or certChain.getNumCerts() == 0:
  1308.             for result in self._sendError(AlertDescription.illegal_parameter, 'Other party sent a Certificate message without certificates'):
  1309.                 yield result
  1310.             
  1311.         
  1312.         publicKey = certChain.getEndEntityPublicKey()
  1313.         if len(publicKey) < settings.minKeySize:
  1314.             for result in self._sendError(AlertDescription.handshake_failure, "Other party's public key too small: %d" % len(publicKey)):
  1315.                 yield result
  1316.             
  1317.         
  1318.         if len(publicKey) > settings.maxKeySize:
  1319.             for result in self._sendError(AlertDescription.handshake_failure, "Other party's public key too large: %d" % len(publicKey)):
  1320.                 yield result
  1321.             
  1322.         
  1323.         yield (publicKey, certChain)
  1324.  
  1325.  
  1326.